
#include "3d_material.h"

using namespace WtfGraphics;


/**** Material Binding ****/

MaterialBinding::MaterialBinding(const WtfEngine::String& sName, const Material::tCacheRef& rMaterial, const GraphicsData::tCacheRef& rGfx)
: GraphicsData(sName), mrMaterial(rMaterial), mrGraphics(rGfx) {
};

void MaterialBinding::render() {
	mrMaterial->Activate();
	mrGraphics->render();
	mrMaterial->Deactivate();
};



/**** Material ****/

Material::MaterialCreationOptions::MaterialCreationOptions()
: vDiffuse(0.5, 0.5, 0.5, 1.0), vSpecular(0, 0, 0),
  vEmissive(0.0, 0.0, 0.0), fPower(0) {
};

Material::Material(const WtfEngine::StringPool::Entry &sName)
: WtfEngine::DataObject(sName) {
};

Material::Material(const WtfEngine::StringPool::Entry &sName, const Material::tCreationOptions& opts)
: WtfEngine::DataObject(sName), mvDiffuse(opts.vDiffuse), mvSpecular(opts.vSpecular),
  mvEmissive(opts.vEmissive), mfPower(opts.fPower) {
};

void Material::Activate() {
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mvDiffuse.toArray());
	glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mvSpecular.toArray());
	glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mvEmissive.toArray());
	glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0);
};

void Material::Deactivate() {

};


/**** Basic Diffuse Texture ****/

DiffuseTextureMaterial::DiffuseTextureMaterial(const WtfEngine::StringPool::Entry &sName)
: Material(sName) {
};

DiffuseTextureMaterial::DiffuseTextureMaterial(const WtfEngine::StringPool::Entry &sName,
	const DiffuseTextureMaterial::tCreationOptions& opts)
: Material(sName, opts), mrTexture(opts.rTexture) {
};

void DiffuseTextureMaterial::Activate() {
	Material::Activate();

	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	mrTexture->Bind();
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
};

void DiffuseTextureMaterial::Deactivate() {
	mrTexture->Release();
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	Material::Deactivate();
};

WtfEngine::IDataObject * DefaultDiffuseTextureMaterial::Load(const WtfEngine::StringPool::Entry& sName) {
	DefaultDiffuseTextureMaterial * pMat = new DefaultDiffuseTextureMaterial(sName);
	pMat->mrTexture = WtfEngine::TextureImage::tCacheRef(*sName + ".jpg");
	return pMat;
};
